package com.bootcamp.mall.controller.mall;

/**
 * @program: mall
 * @author: Keyu Li
 * @create: 2021-11-12 15:11
 **/

import com.bootcamp.mall.model.Result;
import com.bootcamp.mall.model.bo.malluser.UserSignupLoginBO;
import com.bootcamp.mall.model.bo.user.UpdatePwdBO;
import com.bootcamp.mall.model.bo.user.UpdateUserDataBO;
import com.bootcamp.mall.model.vo.malluser.UserSignupLoginVO;
import com.bootcamp.mall.model.vo.user.UserDataVO;
import com.bootcamp.mall.service.malluser.MallUserService;
import com.bootcamp.mall.service.malluser.MallUserServiceImpl;
import com.bootcamp.mall.service.user.UserService;
import com.bootcamp.mall.service.user.UserServiceImpl;
import com.bootcamp.mall.utils.JSONUtil;
import com.bootcamp.mall.utils.StringUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "MallUserServlet", value = "/api/mall/user/*")
public class MallUserServlet extends HttpServlet {


    // UserService 具体实现类
    MallUserService mallUserService = new MallUserServiceImpl();
    UserService userService = new UserServiceImpl();
    // gson
    Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().replace("/api/mall/user/", "");
        if ("data".equals(op)) {
            opData(request, response);
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().replace("/api/mall/user/", "");
        if ("signup".equals(op)) {
            opSignup(request, response);
        } else if ("login".equals(op)) {
            opLogin(request, response);
        } else if ("updatePwd".equals(op)) {
            opUpdatePwd(request, response);
        } else if ("updateUserData".equals(op)) {
            opUpdateUserData(response, request);
        }
    }

    private void opData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        String token = request.getParameter("token");
        if (StringUtil.isEmpty(token)) {
            writer.println(gson.toJson(Result.error("前端参数异常！")));
            return;
        }
        UserDataVO userVO = userService.showUserData(token);
        userVO.setCode(0);
        writer.println(gson.toJson(Result.ok(userVO)));

    }

    private void opUpdateUserData(HttpServletResponse response, HttpServletRequest request) throws IOException {
        PrintWriter writer = response.getWriter();
        // json解析四联：获取字符串，判断不为空，获取对象，捕获异常判断参数合法
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            UpdateUserDataBO userBO = gson.fromJson(asJsonObject, UpdateUserDataBO.class);
            // 插入到数据库中，返回null表示重名异常
            Integer code = userService.updateUserData(userBO);
            if (code == 0) {
                writer.println(gson.toJson(Result.ok()));
                return;
            } else if (code == 1) {
                writer.println(gson.toJson(Result.error("禁止更新admin信息！")));
                return;
            } else if (code == 2) {
                writer.println(gson.toJson(Result.error("昵称禁止设置为admin！")));
                return;
            }
            writer.println(gson.toJson(Result.error("昵称已存在！")));
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("服务器异常！")));
        }

    }

    private void opUpdatePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        System.out.println("userId: "+request.getSession().getAttribute("userId"));
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        // 解析 json 为对象
        PrintWriter writer = response.getWriter();
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            UpdatePwdBO updatePwdBO = gson.fromJson(asJsonObject, UpdatePwdBO.class);
            // 插入到数据库中，返回null表示重名异常
            Integer code = mallUserService.updatePwd(updatePwdBO);
            if (code==0){
                response.getWriter().println(gson.toJson(Result.ok()));
            }
            else if (code == -1) {
                writer.println(gson.toJson(Result.error("修改失败，新密码至少8位！")));
                return;
            } else if (code == -2) {
                writer.println(gson.toJson(Result.error("修改失败，确认密码不一致！")));
                return;
            } else if (code == -3) {
                writer.println(gson.toJson(Result.error("修改失败，用户名或密码不匹配！")));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("参数异常！！")));
            return;
        }
        writer.println(gson.toJson(Result.error("服务器异常，登陆失败！")));
    }

    private void opLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // json解析四联：获取字符串，判断不为空，获取对象，捕获异常判断参数合法
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            UserSignupLoginBO userBO = gson.fromJson(asJsonObject, UserSignupLoginBO.class);
            // 插入到数据库中，返回null表示重名异常
            UserSignupLoginVO userVO = mallUserService.login(userBO);
            if (userVO == null) {
                writer.println(gson.toJson(Result.error("用户名或密码不匹配，登录失败！")));
                return;
            }
            // 登陆成功，则创建session并写入userId
            request.getSession().setAttribute("userId", userVO.getUserId());
            writer.println(gson.toJson(Result.ok(userVO)));
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("登陆失败！")));
        }
    }

    private void opSignup(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // json解析四联：获取字符串，判断不为空，获取对象，捕获异常判断参数合法
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            UserSignupLoginBO userBO = gson.fromJson(asJsonObject, UserSignupLoginBO.class);
            // 插入到数据库中，返回null表示重名异常
            UserSignupLoginVO userVO = mallUserService.signup(userBO);
            if (userVO == null) {
                writer.println(gson.toJson(Result.error("已有同名email或昵称！")));
                return;
            }
            // 注册并登陆成功，则创建session并写入userId
            request.getSession().setAttribute("userId", userVO.getUserId());
            writer.println(gson.toJson(Result.ok(userVO)));
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("参数异常！")));
        }
    }
}
